<?php

namespace api\controller;

// +----------------------------------------------------------------------
// | EXCEL数据控制层
// +----------------------------------------------------------------------

use common\controller\VerifyController;
use common\exception\LogicException;
use common\service\ExportBusinessExcelService;
use common\service\FieldService;
use common\service\ImportExcelService;
use common\validate\Task as TaskValidate;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use support\ErrorCode;
use think\Exception;
use think\module\Module;
use think\Request;
use think\Response;
use think\response\Download;

class ExcelController extends VerifyController
{
    /**
     * 导入excel
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function import(Request $request)
    {
        $param = $request->param();
        $importExcelService = new ImportExcelService();
        $resData = $importExcelService->importExcelData($param, Module::$moduleDictData["module_index_by_code"][$request->getModuleCode()]);
        return json(success_response('', $resData));
    }

    /**
     * 导出excel
     * @param Request $request
     * @return \think\Response
     */
    public function exportExcel(Request $request)
    {
        $resData = [];
        return json($resData);
    }

    /**
     * 格式化Excel粘贴
     * @param Request $request
     * @return \think\Response
     */
    public function formatExcelPasteData(Request $request)
    {
        $param = $request->param();

        $importExcelService = new ImportExcelService();

        $importExcelService->paste($param["parsed"]);
        $hasHeader = $param["has_header"] == 'no' ? false : true;
        $importExcelService->setHeaderStatus($hasHeader);

        $fieldService = FieldService::getInstance();
        $fieldsData = $fieldService->getExcelImportFields($param["module_code"]);

        $excelData = [
            'header' => $importExcelService->getHeader(),
            'body' => $importExcelService->getBody(),
            'fields' => $fieldsData
        ];
        return json(success_response('', $excelData));
    }

    /**
     * 上传Excel文件处理
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function formatExcelFileData(Request $request)
    {
        $param = $request->param();

        $tempFiles = $request->file();

        if (count($tempFiles) == 0) {
            throw_strack_exception("missing upload file", ErrorCode::UPLOAD_FILE_NOT_EXIST);
        }
        /** @var \think\File $tempFile */
        $tempFile = array_pop($tempFiles);
        $extension = $tempFile->getExtension();
        if (in_array($extension, ['csv', 'xls', 'xlsx'])) {
            $importExcelService = new ImportExcelService();
            $fieldService = FieldService::getInstance();

            // 上传文件到临时目录
            $batchNumber = $request->getBatchNumber();
            $tempExcelRelativePath = "/uploads/temp/excel/excel_{$batchNumber}/";
            $tempExcelPath = public_path() . $tempExcelRelativePath;

            create_directory($tempExcelPath);
            $excelTempName = 'excel_' . string_random(8);
            $targetFile = $tempExcelPath . $excelTempName . "." . $extension;

            if (!file_exists($tempFile)) {
                throw_strack_exception(" tempPath {$tempFile->getPathname()}  not exist", ErrorCode::UPLOAD_TEMP_PATH_NOT_EXIST);
            }
            $newFile = $tempFile->move($targetFile);
            if (!$newFile) {
                throw_strack_exception("move upload file failure tempPath {$tempFile->getPathname()} target {$targetFile}", ErrorCode::MOVE_UPLOAD_FILE_FAILURE);
            }

            // 格式化处理数据
            $importExcelService->file($targetFile, $tempExcelRelativePath);
            $hasHeader = $param["has_header"] == 'no' ? false : true;
            $importExcelService->setHeaderStatus($hasHeader);

            $fieldsData = $fieldService->getExcelImportFields($param["module_code"]);

            $excelData = [
                'header' => $importExcelService->getHeader(),
                'body' => $importExcelService->getBody(),
                'images_column' => $importExcelService->getHaveImageCell(),
                'fields' => $fieldsData
            ];

            // 处理完 删除文件
            @unlink($newFile);
            @rmdir($tempExcelPath);
            return json(success_response('', $excelData));
        } else {
            throw_strack_exception('Only allow upload suffixes to .csv, .xls, .xlsx files!', ErrorCode::EXCEL_FILE_EXT_NOT_SUPPORT);
        }
    }

    /**
     * 数据规则检查
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function checkExcelFileData(Request $request)
    {
        $importService = new ImportExcelService();
        $res = $importService->checkExcelFileData($request->param(), $request->param()['project_id'], $request->param()['module_code']);
        return json(success_response('', $res));
    }

    /**
     * 检查表单数据
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function checkFormData(Request $request)
    {
        $importService = new ImportExcelService();
        $res = $importService->checkFormData($request->param(), $request->param()['project_id'], $request->param()['module_code']);
        return json(success_response('', $res));
    }

    /**
     * 导出业务表格
     * @param Request $request
     * @return Download
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public function exportBusinessCodeExcel(Request $request)
    {
        $res = ExportBusinessExcelService::getInstance()->exportBusinessCodeExcel($request->param()['business_code'], $request->param()['export_param']);
        $writer = new Xlsx($res);
        $tempFileName = './temp_' . create_uuid() . time();
        $writer->save($tempFileName);
        $response = new Download(file_get_contents($tempFileName));
        unlink($tempFileName);
        $response->isContent(true);
        $response->mimeType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        $response->name($request->param()['business_code'] . date("YmdHis") . '.xlsx');
        return $response;
    }


    /**
     * 检查任务更新数据
     * @param Request $request
     * @return Response|void
     * @throws Exception
     */
    public function checkUpdateTaskDateData(Request $request)
    {
        $param = $request->param();
        $dataList = $param['data_list'];

        $validate = new TaskValidate();
        foreach ($dataList as $task) {
            if (!$validate->check($task, null, 'CheckUpdateTaskDateDataItem')) {
                throw_strack_exception($validate->getError(), ErrorCode::DATA_INVALID);
            }
        }
        try {
            $importService = new ImportExcelService();
            $res = $importService->checkUpdateTaskDateData($dataList, $param['project_id']);
            return json(success_response('OK', $res));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }
}
